/**
 * 格式化日期时间
 * @param {string|Date} dateString - 日期字符串或Date对象
 * @param {string} format - 格式化字符串，默认为'yyyy-MM-dd HH:mm:ss'
 * @returns {string} 格式化后的日期时间字符串
 */
export function formatDate(dateString, format = 'yyyy-MM-dd HH:mm:ss') {
  let date = null;
  
  if (dateString instanceof Date) {
    date = dateString;
  } else if (typeof dateString === 'string') {
    // 尝试解析日期字符串
    date = new Date(dateString);
    
    // 如果是无效日期，尝试替换格式
    if (isNaN(date.getTime())) {
      // 处理可能的格式问题，如yyyy-MM-ddThh:mm:ss
      dateString = dateString.replace(/-/g, '/').replace('T', ' ');
      date = new Date(dateString);
    }
  } else {
    date = new Date();
  }
  
  if (isNaN(date.getTime())) {
    return 'Invalid Date';
  }
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return format
    .replace('yyyy', year)
    .replace('MM', month)
    .replace('dd', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
}

/**
 * 获取相对时间描述
 * @param {string|Date} dateString - 日期字符串或Date对象
 * @returns {string} 相对时间描述
 */
export function timeAgo(dateString) {
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    return 'Invalid Date';
  }
  
  const now = new Date();
  const diffInSeconds = Math.floor((now - date) / 1000);
  
  if (diffInSeconds < 60) {
    return `${diffInSeconds}秒前`;
  }
  
  const diffInMinutes = Math.floor(diffInSeconds / 60);
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`;
  }
  
  const diffInHours = Math.floor(diffInMinutes / 60);
  if (diffInHours < 24) {
    return `${diffInHours}小时前`;
  }
  
  const diffInDays = Math.floor(diffInHours / 24);
  if (diffInDays < 30) {
    return `${diffInDays}天前`;
  }
  
  const diffInMonths = Math.floor(diffInDays / 30);
  if (diffInMonths < 12) {
    return `${diffInMonths}个月前`;
  }
  
  const diffInYears = Math.floor(diffInMonths / 12);
  return `${diffInYears}年前`;
}

export default {
  formatDate,
  timeAgo
};